<?php defined('BASEPATH') or exit('No direct script access allowed');

class User_m extends MY_Model {	
	function __construct(){
		parent::__construct();
	//	$this->load->library('digit');
	//	$this->load->library('email_sender');
		$this->load->helper('captcha');
	}
	
	function _redirectUser(){
		//redirect if user logon
		if(isset($_SESSION['user'])){
			$USER = $this->user_entity->init('email', $_SESSION['user']['email']);
			if($USER->whoAmI() == 'buyer'){
				redirect(site_url('buyer'));
			}elseif($USER->whoAmI() == 'seller'){
				redirect(site_url('seller'));
			}else{
				show_404( );
				exit();
			}
		}elseif( $this->uri->segment(2,'') == '' ){
			redirect(site_url());
		}
	}
	
	function _createNewCaptcha(){
		$_SESSION['captcha'] =  $this->digit->rand_string(6);
		
		$vals = array(
			'word' => $_SESSION['captcha'],
			'img_path' => './captcha/images/',
			'img_url' => site_url().'captcha/images/',
			'font_path' => './captcha/fonts/arial.ttf',
			'img_width' => '130',
			'img_height' => '40',
			'expiration' => 7200
			);

		$cap = create_captcha($vals);
		return $cap['image'];
	}
	
	function signin(){
		$buyerAccountType = array(
			'general'			=>	'General',
			'corporate_brand'	=>	'Corporate Brand'
		);
		$buyerType = form_dropdown( 'buyer_type',
										$options = $buyerAccountType,
										$selected = array(),
										"id='buyer_type' class='width270'"
									);
		$country = form_dropdown( 'country',
										$options = countriesOnTheWorldDataConfig(),
										$selected = array(),
										"id='country' class='width270'"
									);
		$showType = "<table><tr>";
		$i = 0;
		foreach ( showTypeDataConfig() as $key => $value ){
			if($i % 2 == 0 AND $i!= 0){
				$showType .= "</tr><tr>";
			}
			$i++;
			$showType .= "<td width='250px;'><input type='checkbox' name='show_type[]' id='show_type[]' value='$key' />&nbsp;$value </td>";
		}		
		$showType .= "</tr></table>";
		
	/*	$showType = form_multiselect( 'show_type[]',
										$options = showTypeDataConfig(),
										$selected = array(),
										" size='".count(showTypeDataConfig())."' "
									);	*/
	/*	$countryOrigin = form_multiselect( 'country_origin[]',
										$options = countryOriginDataConfig(),
										$selected = array(),
										" size='".count(countryOriginDataConfig())."' class='width270'"
									);		*/
									
		$countryOrigin = "<table><tr>";
		$i = 0;
		foreach ( countryOriginDataConfig() as $key => $value ){
			if($i % 3 == 0 AND $i!= 0){
				$countryOrigin .= "</tr><tr>";
			}
			$i++;
			$countryOrigin .= "<td width='250px;'><input type='checkbox' name='country_origin[]' id='country_origin[]' value='$key' />&nbsp;$value </td>";
		}		
		$countryOrigin .= "</tr></table>";	
		
		$musicGenre = "<table><tr>";
		$i = 0;
		foreach ( musicGenreDataConfig() as $key => $value ){
			if($i % 3 == 0 AND $i!= 0){
				$musicGenre .= "</tr><tr>";
			}
			$i++;
			$musicGenre .= "<td width='250px;'><input type='checkbox' name='music_genre[]' id='music_genre[]' value='$key' />&nbsp;$value </td>";
		}		
		$musicGenre .= "<td width='250px;'><input type='checkbox' name='checkall_music' id='checkall_music' />&nbsp;<b>Check All</b></td>";
		$musicGenre .= "</tr></table>";		
	/*		
		$musicGenre = form_multiselect( 'music_genre[]',
										$options = musicGenreDataConfig(),
										$selected = array(),
										" size='".count(musicGenreDataConfig())."' "
									); */
		$captcha = $this->_createNewCaptcha();
		return array('country'=>$country, 'show_type'=>$showType,'buyer_type'=>$buyerType, 'country_origin'=>$countryOrigin,'music_genre'=>$musicGenre,'captcha'=>$captcha,'capchaMD5'=>md5($_SESSION['captcha']));	
	}
	
	function submit(){	
		$USER_EXISTED = $this->user_entity->init('email', $this->input->post('email',''));
		if($USER_EXISTED){
			echo "<span class='red'>"."The email you entered already exists"."</span>";
		}else{
			unset($USER_EXISTED);
			$newUserId = $this->user_entity->createNewUserEntity($this->input->post('email',''));
			$USER_EXISTED = $this->user_entity->init('id', $newUserId);
			
			$company_profile = "";
			if(isset($_FILES["company_profile"]) AND !empty($_FILES["company_profile"]['name'])){
				if(($_FILES["company_profile"]['size']/1000000) > allowMaxFileSize() ){
					$company_profile = '';
				}else{
					$company_profile = $this->module_helper->uploadFile( 
											$_FILES["company_profile"]['tmp_name'],
											$_FILES["company_profile"]['name'],
											$USER_EXISTED->getFolderFileStorage(),
											allowExtensionFileDocumentUpload()
										);
				}	
			}
			
			$array_init = array('show_type', 'country_origin', 'music_genre');
			foreach($array_init as $element){
				if(!isset($_POST[$element])){
					$_POST[$element] = array();
				}
			}
			$USER_EXISTED->setPassword( $this->digit->rand_string(6) );
			$USER_EXISTED->setAccCode( $this->digit->generateDigit4User( $this->input->post('type_acc','') ) );
			$USER_EXISTED->setAccType( $this->input->post('type_acc','') );
			$USER_EXISTED->setFirstName( $this->input->post('first_name','') );
			$USER_EXISTED->setLastName( $this->input->post('last_name','') );
			$USER_EXISTED->setJobTitle( $this->input->post('job_title','') );
			$USER_EXISTED->setCompany( $this->input->post('company','') );
			$USER_EXISTED->setCompanyUrl( $this->input->post('company_url','') );
			$USER_EXISTED->setCompanyProfile( $company_profile );
			$USER_EXISTED->setCountry( $this->input->post('country','') );
			$USER_EXISTED->setAddressLine1( $this->input->post('address_line_1','') );
			$USER_EXISTED->setAddressLine2( $this->input->post('address_line_2','') );
			$USER_EXISTED->setCity( $this->input->post('city','') );
			$USER_EXISTED->setState( $this->input->post('state','') );
			$USER_EXISTED->setZip( $this->input->post('zip','') );
			$USER_EXISTED->setWorkPhone( $this->input->post('work_phone','') );
			$USER_EXISTED->setMobile( $this->input->post('mobile','') );
		//	$USER_EXISTED->setBankNameAcc( $this->input->post('bank_name_acc','') );
		//	$USER_EXISTED->setBankAccNo( $this->input->post('bank_acc_no','') );
		//	$USER_EXISTED->setBankName( $this->input->post('bank_name','') );
		//	$USER_EXISTED->setBankAddress( $this->input->post('bank_address','') );
		//	$USER_EXISTED->setSwiftCode( $this->input->post('swift_code','') );
			$USER_EXISTED->setExpiredTime( time()+5*86400 );
			$USER_EXISTED->setCreatedDate( time() );
			//if( $this->input->post('type_acc','') == 'buyer' ){
			$USER_EXISTED->setShowType( implode(',',$_POST['show_type']) );
			$USER_EXISTED->setCountryOrigin( implode(',',$_POST['country_origin']) );
			$USER_EXISTED->setMusicGenre( implode(',',$_POST['music_genre']) );
			//}
			$USER_EXISTED->setStatus( 'active' );
			$USER_EXISTED->setBuyerType( $this->input->post('buyer_type','') );
			
			$USER_EXISTED->update();
			
			$this->crontab_email->cronUpdate($USER_EXISTED->getAccCode(),'_sendEmailToUser_confirm', $USER_EXISTED->getId(), array(time()) );
			
			echo 'ok';
		}
		
		exit();
	}
	
	function submit_login(){
		$USER_EXISTED = $this->user_entity->init('email', $this->input->post('email',''));
		if($USER_EXISTED){
			if( $this->input->post('password','') == $USER_EXISTED->getPasswd() AND $USER_EXISTED->getStatus() == 'active' )	// 
			{
				$_SESSION['user'] = array('id'=>$USER_EXISTED->getId(),'email'=>$USER_EXISTED->getEmail(), 'firstName'=>$USER_EXISTED->getFirstName(), 'lastName'=>$USER_EXISTED->getLastName());
				echo site_url($USER_EXISTED->whoAmI());
				exit();
			}else
			{
				echo 'nok';exit();
			}
		}else
		{
			echo 'nok';exit();
		}
	}
	
	function submit_email_forgot(){
		$USER_EXISTED = $this->user_entity->init('email', $this->input->post('email',''));
		if( !$USER_EXISTED ){
			echo 'nok';exit();
		}else{
			$USER_EXISTED->setActivatedCode($this->digit->rand_string(6));
			$USER_EXISTED->update();
			
			$this->crontab_email->cronUpdate( $USER_EXISTED->getAccCode(), '_sendEmailToUser_forgotPassword', $USER_EXISTED->getId(), array(time()) );
			
			echo 'ok';exit();
		}
	}
	
	function regenerate_password(){
		$USER_EXISTED = $this->user_entity->init('email', $_GET['email']);
		if(!$USER_EXISTED ){
			return array('stt'=>'err', 'msg'=>"Email does not exist");
		}elseif( md5( $USER_EXISTED->getActivatedCode() ) != $_GET['code'] ){
			return array('stt'=>'err', 'msg'=>"Oops! Something has gone wrong!");
		}else{
			$USER_EXISTED->setPassword( $USER_EXISTED->getActivatedCode() );
			$USER_EXISTED->update();
			return array('stt'=>'ok', 'msg'=>"Success! Now you can use your new password.");
		}
	}
	
	function confirm(){
		$USER_EXISTED = $this->user_entity->init('id', $_GET['id']);
		if(!$USER_EXISTED ){
			return array('stt'=>'err', 'msg'=>"This user does not exist in the system.");
		}elseif( md5( $USER_EXISTED->getPasswd() ) != $_GET['code'] ){
			return array('stt'=>'err', 'msg'=>"Oops! Something has gone wrong!");
		}else{
			$USER_EXISTED->setStatus( 'confirm' );
			$USER_EXISTED->update();
			return array('stt'=>'ok', 'msg'=>"Thank you for your application. Our administrator will be in touch with you within the next few days.");
		}
	}
	
	
	
	
	
	
}